package com.jimster.plugins.gadgets.tree
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class TreeParser extends EventDispatcher
	{
		//Variables
		private var ldrXml:URLLoader;
		private var xmlData:XML;
		private var strTopLevelChild:String;
		private var strSubLevelChild:String;
		
		//Constructor
		public function TreeParser()
		{
			super();
		}
		
		//Public methods
		public function initialize( $xmlPath:String, $topLevelChild:String="", $subLevelChild:String="" ):void
		{
			this.strTopLevelChild = $topLevelChild;
			this.strSubLevelChild = $subLevelChild;
			this.ldrXml = new URLLoader();
			this.ldrXml.addEventListener( Event.COMPLETE, this.onXmlLoaded );
			this.ldrXml.load( new URLRequest( $xmlPath ) );
		}
		//Private methods
		private function parseTopLevelChilds():void
		{
			for( var item:String in this.xmlData[this.strTopLevelChild] )
			{
				trace( this.xmlData[this.strTopLevelChild][item].name );
				
				if( this.xmlData[this.strTopLevelChild][item].children( ) )
				{
					this.parseSubLevelChilds( this.xmlData[this.strTopLevelChild][item] );
				}
			}
		}
		
		private function parseSubLevelChilds( $xml:XML ):void
		{
			for( var item:String in $xml[this.strSubLevelChild] )
			{
				trace( $xml[this.strSubLevelChild][item].name );
				
				if( $xml[this.strSubLevelChild][item].children( ) )
				{
					this.parseSubLevelChilds( $xml[this.strSubLevelChild][item] );
				}
			}
		}
		
		//Event handlers
		private function onXmlLoaded( $event:Event ):void
		{
			this.xmlData = new XML( $event.target.data );
			this.parseTopLevelChilds();
		}
	}
}